#include "../http/httpserver.hpp"

void PersistentTest()
{
    Socket cli_sock;
    cli_sock.CreateClient(8050, "127.0.0.1");
    std::string req = "GET /hello HTTP/1.1\r\nConnection: keep-alive\r\nContent-Length: 0\r\n\r\n";
    while(true)
    {
        assert(cli_sock.Send(req.c_str(), req.size()) != -1);
        char buffer[1024] = {0};
        assert(cli_sock.Recv(buffer, 1023) != -1); 
        logMessage(NORMAL, "\n%s", buffer);
        sleep(3);
    }
    cli_sock.Close();
}

void TimeoutTest1()
{
    Socket cli_sock;
    cli_sock.CreateClient(8050, "127.0.0.1");
    std::string req = "GET /hello HTTP/1.1\r\nConnection: keep-alive\r\nContent-Length: 0\r\n\r\n";
    while(true)
    {
        assert(cli_sock.Send(req.c_str(), req.size()) != -1);
        char buffer[1024] = {0};
        assert(cli_sock.Recv(buffer, 1023) != -1); 
        logMessage(NORMAL, "\n%s", buffer);
        sleep(15);
    }
    cli_sock.Close();
}

void TimeoutTest2()
{
    signal(SIGCHLD, SIG_IGN);
    for(int i = 0; i < 10; i++)
    {
        pid_t pid = fork();
        if(pid < 0)
            return;
        else if(pid == 0)
        {
            Socket cli_sock;
            cli_sock.CreateClient(8050, "127.0.0.1");
            std::string req = "GET /hello HTTP/1.1\r\nConnection: keep-alive\r\nContent-Length: 0\r\n\r\n";
            while(true)
            {
                assert(cli_sock.Send(req.c_str(), req.size()) != -1);
                char buffer[1024] = {0};
                assert(cli_sock.Recv(buffer, 1023) != -1); 
                logMessage(NORMAL, "\n%s", buffer);
            }
            cli_sock.Close();
            return;
        }
    }
    while(1) sleep(1);
}

void LessDataTest()
{
    Socket cli_sock;
    cli_sock.CreateClient(8050, "127.0.0.1");
    std::string req = "GET /hello HTTP/1.1\r\nConnection: keep-alive\r\nContent-Length: 16\r\n\r\nHello World\r\n";
    for(int i = 0 ; i < 5 ; i++)
    {
        assert(cli_sock.Send(req.c_str(), req.size()) != -1);
        sleep(1);
    }
    
    char buffer[1024] = {0};
    assert(cli_sock.Recv(buffer, 1023) != -1); 
    logMessage(NORMAL, "\n%s", buffer);
    sleep(1);
    cli_sock.Close();
}

void LargeTest()
{
    Socket cli_sock;
    cli_sock.CreateClient(8050, "127.0.0.1");
    std::string req = "PUT /1234.txt HTTP/1.1\r\nConnection: keep-alive\r\n";
    std::string body;
    Util::ReadFile("hello.txt", &body);
    req += "Content-Length: " + std::to_string(body.size()) + "\r\n\r\n";
    assert(cli_sock.Send(req.c_str(), req.size()) != -1);
    assert(cli_sock.Send(body.c_str(), body.size()) != -1);
    char buffer[1024] = {0};
    assert(cli_sock.Recv(buffer, 1023) != -1); 
    logMessage(NORMAL, "\n%s", buffer);
    cli_sock.Close();
}

int main()
{
    TimeoutTest1();
    return 0;
}